﻿#pragma once
// Copyright (c) lanyeo 2020-2021
// Licenced under MIT license. See https://opensource.org/licenses/MIT for details.
// code style
// 1. use forward declaration (尽可能使用前置声明)
// 2. include file sequence [other project>c>c++>third>self project]
//

#include <cstdint>
#include <chrono>
#include <ctime>
#include <string>

namespace fist
{
    // 毫秒
    typedef int64_t ms_t;
    typedef int64_t us_t;

    inline ms_t get_now_ms_time()
    {
        return std::chrono::duration_cast<std::chrono::milliseconds>(
            std::chrono::system_clock::now().time_since_epoch()
            ).count();
    }

    inline ms_t get_now_us_time()
    {
        return std::chrono::duration_cast<std::chrono::microseconds>(
            std::chrono::system_clock::now().time_since_epoch()
            ).count();
    }
    inline std::string get_now_format_time(const char* fmt)
    {
        time_t now = time(0);
        char buf[256];
#ifdef _MSC_VER
        tm tm;
        gmtime_s(&tm, &now);
        size_t l = std::strftime(buf, 256, fmt, &tm);
#else
        std::tm* tm = gmtime(&now);
        size_t l = std::strftime(buf, 256, fmt, tm);
#endif
        buf[l] = '\0';
        return buf;
    }

#define CHECK_TIMEOUT(LAST, INTERVAL, EXEC, ...) \
if (fist::get_now_ms_time() - (LAST) > (INTERVAL)) { \
    EXEC(__VA_ARGS__); \
    (LAST) = fist::get_now_ms_time(); \
}

}
